package com.iamgod.savemoney.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * @author lihui
 * android http������
 * ��װhttp���ʷ���
 *
 */
public class HttpUtil {

	private static int timeoutConnection = 10000;   
	private static int timeoutSocket = 15000; 
	private static String TAG = "HttpUtils";
	
	
	
	/**
	 * get方式获取Http返回数据
	 * @param url
	 * @param params
	 * @return
	 */
	public static String getHttpContextByGet(String url,HashMap<String,String> params){
		
		Log.i(TAG, url);
		HttpGet httpRequest = new HttpGet(url+HttpUtil.getParamsStrFromMap(params));
		try
		{
			HttpParams  httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.   
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
			//ȡ��HttpClient����
			HttpClient httpclient = new DefaultHttpClient(httpParameters);
			//����HttpClient��ȡ��HttpResponse
			
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				//ȡ�÷��ص��ַ�
				return EntityUtils.toString(httpResponse.getEntity());
			}
			else
			{
				return null;
			}
		}
		catch (Exception e)
		{
			Log.e(TAG, e.getMessage().toString());
			return null;
		}
	}
	
	
	
	/**
	 * Post方式获取http内容
	 * @param url
	 * @param params
	 * @return
	 */
	public static String getHttpContextByPost(String url,HashMap<String,String> params){
		Log.i(TAG, url);
		HttpPost httpRequest = new HttpPost(url);
		List<BasicNameValuePair> paramsList = new ArrayList<BasicNameValuePair>();
		paramsList = HttpUtil.getParamsListFromMap(params);
		try
		{
			HttpParams  httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.   
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
			//�����ַ�
			HttpEntity httpentity = new UrlEncodedFormEntity(paramsList, "utf-8");
			httpRequest.setEntity(httpentity);
			
			//ȡ��HttpClient����
			HttpClient httpclient = new DefaultHttpClient(httpParameters);
			
			
			//����HttpClient��ȡ��HttpResponse
			
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				//ȡ�÷��ص��ַ�
				return EntityUtils.toString(httpResponse.getEntity());
			}
			else
			{
				return null;
			}
		}
		catch (Exception e)
		{
			Log.e(TAG, e.getMessage().toString());
			return null;
		}
	}
	
	/**
	 * HashMap对象转get字符串
	 * ����װ��HashMap�е�ֵ�����http�ķ��ʲ����ַ�,����" ?key1=value1&key2=value2 ",����get��ʽ����
	 * @param params
	 * @return
	 */
	public static String getParamsStrFromMap(HashMap<String, String> params){
		if(params==null){
			return "";
		}
		StringBuffer sb = new StringBuffer();
		Iterator<?> it = params.entrySet().iterator();
		int i = 0;
	    while (it.hasNext()) {
	        Map.Entry entry = (Map.Entry) it.next();
	        String key = (String) entry.getKey();
	        String value = (String) entry.getValue(); 
	        if(i==0){
	        	sb.append("?"+key+"="+value);
	        }else{
	        	sb.append("&"+key+"="+value);
	        }
	        i++;
	    }
	    //Log.i(TAG,sb.toString());
	    return sb.toString();
	}
	
	
	/**
	 * map转post参数
	 * ����װ��HashMap�е�ֵ�����http�ķ��ʲ���List<BasicNameValuePair> ,����post��ʽ����
	 * @param params
	 * @return
	 */
	public static List<BasicNameValuePair> getParamsListFromMap(HashMap<String, String> params){
		if(params==null){
			return null;
		}
		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
		Iterator<?> it = params.entrySet().iterator();
		int i = 0;
	    while (it.hasNext()) {
	        Map.Entry entry = (Map.Entry) it.next();
	        String key = (String) entry.getKey();
	        String value = (String) entry.getValue(); 
	        Log.i(TAG, "key="+key+",value="+value);
	        list.add(new BasicNameValuePair(key,value));
	    }
		return list;
		
	}
	
	
	
	 public static String delHTMLTag(String htmlStr){ 
	        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //����script��������ʽ 
	        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //����style��������ʽ 
	        String regEx_html="<[^>]+>"; //����HTML��ǩ��������ʽ 
	         
	        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE); 
	        Matcher m_script=p_script.matcher(htmlStr); 
	        htmlStr=m_script.replaceAll(""); //����script��ǩ 
	         
	        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE); 
	        Matcher m_style=p_style.matcher(htmlStr); 
	        htmlStr=m_style.replaceAll(""); //����style��ǩ 
	         
	        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); 
	        Matcher m_html=p_html.matcher(htmlStr); 
	        htmlStr=m_html.replaceAll(""); //����html��ǩ 
	        
	        htmlStr = htmlStr.replace("&nbsp;", " ");

	        return htmlStr.trim(); //�����ı��ַ� 
	    } 

	 
	 public static Bitmap getBitmap(String imageUrl){  
		         Bitmap mBitmap = null;  
		         try {  
		             URL url = new URL(imageUrl);  
		             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
		             InputStream is = conn.getInputStream();  
		             mBitmap = BitmapFactory.decodeStream(is);  
		              
		        } catch (MalformedURLException e) {  
		             e.printStackTrace();  
		        } catch (IOException e) {  
		           e.printStackTrace();  
		        }  
		         

		         return mBitmap;  
		    }


}
